import { AlertCircle, Save } from "lucide-react";
import React, { useEffect, useId, useState } from "react";
import { Link, redirect, useNavigate, useParams } from "react-router";
import type { ArticleUpdateInput, ArticleView } from "../../../apis/article";
import apis from "../../../apis/article";
import useMeStore from "../../../store/me";

export default function ArticleEditPage() {
  const { id } = useParams();
  const { me, loadMe } = useMeStore();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [loadingArticle, setLoadingArticle] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [article, setArticle] = useState<ArticleView | null>(null);
  const [formData, setFormData] = useState<ArticleUpdateInput>({
    title: "",
    content: "",
  });
  const [formErrors, setFormErrors] = useState<Record<string, string>>({
    title: "",
    content: "",
  });

  // 使用 useId 生成唯一 id
  const titleId = useId();
  const contentId = useId();

  // 检查用户是否登录
  React.useEffect(() => {
    const checkLoginStatus = async () => {
      await loadMe();
    };
    checkLoginStatus();
  }, [loadMe]);

  // 如果用户未登录，重定向到登录页
  React.useEffect(() => {
    if (me.type !== "loading" && me.type !== "ok") {
      redirect("/login");
    }
  }, [me]);

  // 加载文章数据
  useEffect(() => {
    const loadArticle = async () => {
      if (!id) {
        setError("文章ID不存在");
        setLoadingArticle(false);
        return;
      }

      try {
        setLoadingArticle(true);
        setError(null);
        const articleData = await apis.articleGet(id);
        setArticle(articleData);
        setFormData({
          title: articleData.title,
          content: articleData.content,
        });
      } catch (err) {
        setError("获取文章详情失败，请稍后再试");
        console.error("Failed to load article:", err);
      } finally {
        setLoadingArticle(false);
      }
    };

    if (me.type === "ok") {
      loadArticle();
    }
  }, [id, me.type]);

  // 检查当前用户是否是文章作者
  const isAuthor = React.useMemo(() => {
    if (!article?.author || me.type !== "ok") {
      return false;
    }
    return article.author.nickname === me.data.nickname;
  }, [article, me]);

  // 处理表单输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setFormData((prev) => ({
      ...prev,
      [name]: value,
    }));

    // 清除对应字段的错误信息
    if (formErrors[name]) {
      setFormErrors((prev) => ({
        ...prev,
        [name]: "",
      }));
    }
  };

  // 验证表单
  const validateForm = (): boolean => {
    const errors: Record<string, string> = {};

    if (!formData.title.trim()) {
      errors.title = "标题不能为空";
    }

    if (!formData.content.trim()) {
      errors.content = "内容不能为空";
    }

    setFormErrors(errors);
    return Object.keys(errors).length === 0;
  };

  // 处理表单提交
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!validateForm()) {
      return;
    }

    if (me.type !== "ok") {
      setError("请先登录");
      return;
    }

    if (!id) {
      setError("文章ID不存在");
      return;
    }

    if (!isAuthor) {
      setError("您没有权限编辑此文章");
      return;
    }

    try {
      setLoading(true);
      setError(null);

      await apis.articleUpdate(id, formData);

      // 文章更新成功后跳转到文章详情页
      navigate(`/articles/${id}`);
    } catch (err) {
      setError("更新文章失败，请稍后再试");
      console.error("Failed to update article:", err);
    } finally {
      setLoading(false);
    }
  };

  // 渲染加载中状态
  if (me.type === "loading" || loadingArticle) {
    return (
      <div className="min-h-screen bg-base-100 flex flex-col items-center justify-center">
        <div className="loading loading-spinner loading-lg text-primary" />
        <p className="mt-4 text-base-content/70">加载中...</p>
      </div>
    );
  }

  // 如果用户未登录，这里理论上不会执行到
  if (me.type !== "ok") {
    return null;
  }

  // 如果文章不存在或用户不是作者
  if (!article || !isAuthor) {
    return (
      <div className="min-h-screen bg-base-100 flex flex-col items-center justify-center p-4">
        <div className="max-w-md w-full bg-base-200 rounded-lg shadow-lg p-6 text-center">
          <div className="text-red-500 text-4xl mb-4">❌</div>
          <h2 className="text-xl font-semibold text-base-content mb-2">{!article ? "文章不存在" : "无权限编辑"}</h2>
          <p className="text-base-content/70 mb-6">
            {!article ? "您要编辑的文章不存在或已被删除" : "您没有权限编辑此文章"}
          </p>
          <Link
            to={article ? `/articles/${id}` : "/articles"}
            className="inline-flex items-center px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors"
          >
            {article ? "返回文章详情" : "返回文章列表"}
          </Link>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-base-100">
      {/* 页面头部 */}
      <header className="bg-base-200 shadow-sm">
        <div className="container mx-auto px-4 py-6">
          <div className="flex items-center justify-between">
            <h1 className="text-2xl font-bold text-base-content">编辑文章</h1>
            <Link
              to={`/articles/${id}`}
              className="inline-flex items-center px-3 py-1.5 border border-base-300 rounded-md text-sm font-medium text-base-content bg-base-200 hover:bg-base-300 transition-colors"
            >
              取消编辑
            </Link>
          </div>
        </div>
      </header>

      {/* 表单区域 */}
      <main className="container mx-auto px-4 py-8">
        <div className="max-w-2xl mx-auto bg-base-200 rounded-lg shadow-md p-6">
          {error && (
            <div className="alert alert-error mb-4">
              <AlertCircle className="h-5 w-5 shrink-0" />
              <span>{error}</span>
            </div>
          )}

          <form onSubmit={handleSubmit} className="space-y-4">
            {/* 标题输入框 */}
            <div className="space-y-2">
              <label htmlFor={titleId} className="block text-sm font-medium text-base-content">
                标题
              </label>
              <input
                type="text"
                id={titleId}
                name="title"
                value={formData.title}
                onChange={handleInputChange}
                placeholder="请输入文章标题"
                className={`w-full px-4 py-2 border rounded-md focus:ring-2 focus:ring-primary focus:border-primary bg-base-100 text-base-content ${
                  formErrors.title ? "border-red-500" : "border-base-300"
                }`}
                disabled={loading}
              />
              {formErrors.title && <p className="text-sm text-red-500">{formErrors.title}</p>}
            </div>

            {/* 内容输入框 */}
            <div className="space-y-2">
              <label htmlFor={contentId} className="block text-sm font-medium text-base-content">
                内容
              </label>
              <textarea
                id={contentId}
                name="content"
                value={formData.content}
                onChange={handleInputChange}
                placeholder="请输入文章内容"
                rows={10}
                className={`w-full px-4 py-2 border rounded-md focus:ring-2 focus:ring-primary focus:border-primary bg-base-100 text-base-content ${
                  formErrors.content ? "border-red-500" : "border-base-300"
                }`}
                disabled={loading}
              />
              {formErrors.content && <p className="text-sm text-red-500">{formErrors.content}</p>}
            </div>

            {/* 提交按钮 */}
            <div className="pt-4">
              <button type="submit" disabled={loading} className="w-full btn btn-primary">
                {loading ? (
                  <span className="flex items-center justify-center">
                    <div className="loading loading-spinner loading-xs mr-2" />
                    保存中...
                  </span>
                ) : (
                  <span className="flex items-center justify-center gap-2">
                    <Save className="h-5 w-5" />
                    保存更改
                  </span>
                )}
              </button>
            </div>
          </form>
        </div>
      </main>
    </div>
  );
}
